// pages/home/search/search.js
import api from "./../../../common/api"
import {
  mathchSearchValue,
  _debounce
} from './../../../utils/utilsNew';
import * as transferData from './../../../models/transferData'

const STORAGE_FRONT = 'search_history_'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    cityCode: '',
    cityName: '',
    placeholder: '', // 输入提示
    searchValue: '',
    searchTextValue: '',
    historyList: [],
    searchList: [],
    pageIndex: 0,
    pageSize: 15,
    hasMoreList: true,
    loading: false,
    history: '', // 区分不同页面来源隔离历史数据
    isShowHistory: false,
    accurate: '', // 区分不同页面来源调用不同小区接口
    isAccurate: false,
    isHideCount: false,
    name: '',
    isListShow: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.data.isAccurate && this.loadSearchList()
  },

  initData(options) {
    this.setData({
      cityCode: options.citycode || '',
      cityName: options.cityname || '',
      placeholder: options.placeholder || '',
      history: options.history || '',
      isShowHistory: options.history ? true : false,
      accurate: options.accurate || '',
      isAccurate: options.accurate ? true : false,
      accurateType: options.accuratetype || 'id',
      isHideCount: options.count === '1' ? true : false,
      name: options.name || '',
      vague: options.vague === '1' ? true : false,
      isListShow: options.isListShow || ''
    })
    // 带搜索进入
    if (options.search) {
      this.setData({
        searchValue: options.search,
        searchTextValue: options.search,
      })
      this.data.isAccurate && this.loadSearchList()
    }
    // 获取本地历史
    if (this.data.isShowHistory) {
      let historyList = wx.getStorageSync(`${STORAGE_FRONT}${this.data.history}`)
      if (historyList) {
        this.setData({
          historyList
        })
      }
    }

  },

  onInputChange: _debounce(function (e) {
    let keyword = e.detail.value || ''
    this.setData({
      pageIndex: 0,
      hasMoreList: true,
      searchList: [],
      searchTextValue: keyword,
    })
    this.data.isAccurate && this.loadSearchList()
  }, 500),

  loadSearchList() {
    return new Promise((resolve, reject) => {
      const {
        pageIndex,
        pageSize,
        accurate,
        cityCode,
        cityName,
        searchTextValue,
        hasMoreList,
      } = this.data;
      if (!hasMoreList) {
        resolve()
        return
      }
      this.setData({
        loading: true,
      });
      if (!searchTextValue) {
        this.setData({
          loading: false,
        });
        return
      }
      let currentIndex = pageIndex + 1
      api[accurate]({
        city: cityName,
        cityCode: cityCode,
        resblockName: searchTextValue,
        pageNo: currentIndex,
        rows: pageSize,
        page: currentIndex,
        pageSize: pageSize,
      }, res => {
        if (res && res.data && res.data.isSuccess && res.data.content) {
          const result = res.data.content
          let maxIndex = result.total
          let formatList = (result.rows || []).map(item => {
            return {
              contentList: mathchSearchValue(item.resblockName, searchTextValue),
              id: item.hdResblockId || item.resblockId || '',
              name: item.resblockName || '',
              saleTotal: item.salesCount || item.saleTotal || 0,
              rentTotal: item.rentCount || item.rentTotal || 0,
            }
          })
          if (currentIndex === 1) {
            this.data.searchList = [...formatList]
          } else {
            this.data.searchList.push(...formatList)
          }
          this.setData({
            pageIndex: currentIndex,
            hasMoreList: currentIndex >= maxIndex ? false : true,
            searchList: this.data.searchList,
          });
          resolve();
        } else {
          reject()
        }
      }, () => {
        reject()
      })
    })
  },

  onClickSearch(e) {
    let {
      searchList,
      accurateType
    } = this.data || {}
    let index = e.currentTarget.dataset.index
    if (accurateType === 'id') {
      this.jumpToList({
        type: 'id',
        value: searchList[index].id,
        label: searchList[index].name,
      })
    }
    if (accurateType === 'name') {
      this.jumpToList({
        type: 'name',
        value: searchList[index].name,
        label: searchList[index].name,
      })
    }
  },

  onSearchConfirm(e) {
    if (!this.data.vague) return
    let keyword = e.detail.value
    if (!(keyword && keyword.trim())) {
      return wx.showToast({
        title: '请输入搜索词',
        icon: 'none',
      })
    }
    this.jumpToList({
      type: 'key',
      value: keyword,
      label: keyword,
    })
  },

  onSearchConfirmByBtn() {
    let keyword = this.data.searchTextValue
    if (!(keyword && keyword.trim())) {
      return wx.showToast({
        title: '请输入搜索词',
        icon: 'none',
      })
    }
    this.jumpToList({
      type: 'key',
      value: keyword,
      label: keyword,
    })
  },

  onClickHistory(e) {
    let currentIndex = e.target.dataset.index
    this.data.historyList.forEach((item, index) => {
      if (index === currentIndex) {
        this.jumpToList(item)
      }
    })
  },

  jumpToList({
    type,
    value,
    label,
  }) {
    let {
      historyList,
      name
    } = this.data
    if (name) {
      transferData.setTemporaryData(name, {
        type,
        label,
        value,
      })
    } else {
      transferData.setData('commonSearch', {
        type,
        label,
        value,
      })
    }
    if (this.data.isShowHistory) {
      let repetitiveIndex = -1
      historyList.forEach((item, index) => {
        if (item.label === label) {
          repetitiveIndex = index
        }
      })
      if (repetitiveIndex >= 0) {
        historyList.splice(repetitiveIndex, 1)
      }
      historyList.unshift({
        type,
        value,
        label,
      })
      let newHistoryList = historyList.slice(0, 20)
      wx.setStorageSync(`${STORAGE_FRONT}${this.data.history}`, newHistoryList)
    }
    wx.navigateBack()
  },

  onSearchClear() {
    this.setData({
      searchTextValue: '',
      searchValue: '',
      pageIndex: 0,
      hasMoreList: true,
      searchList: [],
    })
  },

  onHistoryClear() {
    wx.showModal({
        content: "确认清空历史搜索记录？"
      })
      .then((res) => {
        if (res.confirm) {
          this.setData({
            historyList: []
          })
          wx.removeStorageSync(`${STORAGE_FRONT}${this.data.history}`)
        }
      })
  },




})